package org.myontology.controller;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;

import org.apache.log4j.Logger;
import org.myontology.init.Globals;
import org.myontology.users.User;

public class Mailer {

	private Logger logger;
	
	public void mail(String mail, String subject, String text,AttributeHolder attributes) throws Exception {
		try {
		Properties props = new Properties();    
		props.put("mail.smtp.host",Globals.smtp.getValue(attributes)  );
		String user = Globals.smtpUser.getValue(attributes);
		String pass = Globals.smtpPass.getValue(attributes);
		Authenticator auth = null;
		if (user!=null && pass!=null) {
			props.put("mail.smtp.auth", true);
			auth = new PopupAuthenticator(user,pass);
		}
		
		Session s = Session.getDefaultInstance(props, auth);
		javax.mail.internet.MimeMessage message = new javax.mail.internet.MimeMessage(s);
		message.setFrom(new InternetAddress( Globals.sender.getValue(attributes)  ));
		message.addRecipient(Message.RecipientType.TO, new InternetAddress( mail ));
		if (Globals.bcc.getValue(attributes)!=null)
			message.addRecipient(Message.RecipientType.BCC, new InternetAddress( Globals.bcc.getValue(attributes)  ));
		message.setSubject(subject);	
		message.setText( text );
		message.saveChanges();
		
		logger.debug("trying to send:");
		logger.debug("subject: "+subject);
		logger.debug("text:"+text);
		logger.debug("with auth:"+auth);
		logger.debug("from: "+Globals.sender.getValue(attributes));
		logger.debug("to: "+mail);
		Transport.send(message);
		}
		catch (Exception e) {
			logger.error(e);
		}
	}
	
	public void mail (User user,String subject, String text,AttributeHolder attributes) throws Exception {
		mail(user.email.getValueString(),subject,text,attributes);
	}
	
	public static class PopupAuthenticator extends Authenticator {
		private String myuser;
		private String mypass;

		public PopupAuthenticator(String user,String pass) {
			myuser=user;
			mypass=pass;
		}
		
		  public PasswordAuthentication getPasswordAuthentication() {
		    return new PasswordAuthentication(myuser, mypass);
		  }
		  @Override
			public String toString() {
				
				return myuser+" "+mypass;
			}
		  }
public void setLogger(Logger logger) {
	this.logger = logger;
}
	
	
}
